//
//  GoodsSepcSelectorCtr-Bar.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/8.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import soapp
import Eelay
import AsyncDisplayKit

extension Goods{
    public static func hasSpec(goods:NSMutableDictionary) ->Bool{
        return goods["goodsoption.hasoption",false.tag] == true.tag
    }
}

//规格选择Next
public enum SpecSelectorNext:String{
    case 加入购物车 = "0"
    case 购买 = "1"
    case 预约 = "50"
    case 团购单买 = "20"
    case 发起团购 = "21"
    case 参与拼团 = "22"
    
    public var gradient:[UIColor]{
        get{
            switch self {
            case .预约:
                return ThemeSet.Gradient.buy
            case .购买:
                return ThemeSet.Gradient.buy
            case .发起团购:
                return ThemeSet.Gradient.buy
            case .参与拼团:
                return ThemeSet.Gradient.buy
            case .团购单买:
                return ThemeSet.Gradient.buy
            case .加入购物车:
                return ThemeSet.Gradient.cart
            default:
                return ThemeSet.Gradient.buy
            }
        }
    }
    
    var name:String{
        get{
            switch self {
            case .预约:
                return "立即预约".loc
            case .购买:
                return "立即购买".loc
            case .发起团购:
                return "发起团购".loc
            case .参与拼团:
                return "参与拼团".loc
            case .团购单买:
                return "单独购买".loc
            default:
                return "加入购物车".loc
            }
        }
    }
    
    static func nextWith(name:String)->SpecSelectorNext?{
        switch name {
        case "立即预约".loc:
            return .预约
        case "立即购买".loc:
            return .购买
        case "发起团购".loc:
            return .发起团购
        case "加入购物车".loc:
            return .加入购物车
        case "单独购买".loc:
            return .团购单买
        case "参与拼团".loc:
            return .参与拼团
        default:
            return nil
        }
    }
    
    var button:ASButtonNode{
        get{

            let bt = ASButtonNode()
            bt.actionID = name
            bt.setBackgroundImage(UIImage.gradient(colors: gradient, size: [120.co,38]), for: .normal)
            _ = bt.ui.ntitle(title: name).ncolor(hex: "#ffff").font(size: 13).set(radius: ThemeSet.buttonRadius, width: nil, color: nil)
            return bt
//            switch self {
//            case .购买:
//                let bt = ASButtonNode()
//                bt.actionID = name
//                bt.setBackgroundImage(UIImage.gradient(colors: gradient, size: [120.co,38]), for: .normal)
//                _ = bt.ui.ntitle(title: name).ncolor(hex: "#ffff").font(size: 13).set(radius: ThemeSet.buttonRadius, width: nil, color: nil)
//                return bt
//            default:
//                let bt = ASButtonNode()
//                bt.actionID = name
//                bt.setBackgroundImage(UIImage.gradient(colors: gradient, size: [120.co,38]), for: .normal)
//                _ = bt.ui.buttonColor(color: ___shop.tint).ntitle(title: name).ncolor(hex: "#fff").font(size: 13).corner4
//                return bt
//            }
        }
    }
}



extension ASButtonNode{
}

open class SpecNextBar: MoDisplayNode {
    
    public var nextPressed:(SpecSelectorNext)->Void = {_ in}
    public var nextActions:[SpecSelectorNext] = [.加入购物车,.购买]{
        didSet{
            weak var ws = self
            bts = nextActions.map({ (next) -> ASButtonNode in
                let bt = next.button
                ws?.assinedActcionToButton(bt)
                return bt
            })
            
            setNeedsLayout()
            setNeedsDisplay()
        }
    }
    
    func assinedActcionToButton(_ button: ASButtonNode)  {
        button.addTarget(self, action: #selector(butttonAction), forControlEvents: .touchUpInside)
    }
    
    
    @objc func butttonAction(sender:ASButtonNode){

        if let next = SpecSelectorNext.nextWith(name: sender.actionID){
            self.nextPressed(next)
        }
        
    }
    
    public var bts = [ASDisplayNode]()
    override open func addLayoutRules() {
        weak var ws = self
        bts = nextActions.map({ (next) -> ASButtonNode in
            let bt = next.button
            ws?.assinedActcionToButton(bt)
            return bt
        })
    }
    
    override open func specGetter() -> _Spec {
        
        let childs = bts.map { (node) -> _Spec in
            return node[_grow(1),_shrink(1)]
        }
        return .stack(["h|\(ThemeSet.buttonSpace)",[0,AppTheme.edge],&-.stretch], childs: childs)
        
    }
}

extension GoodsSepcSelectorCtr
{
    class NumFooter: EeSimpleNumField<EeSimpleNumStepControl1> {
        
        public var specTask = SpecTask.default
       
        override func addLayoutRules() {
            eelay = [
                [numControl,[ee.Y],[ee.R,-AppTheme.edge]],
                [fieldNameL,[ee.L.Y,[AppTheme.edge,0]]],
            ]
            backgroundColor = UIColor.clear
            fieldNameL.text = "数量".loc
            let field:[String:Any] =
                [
                    FK.placeholder:"数量".loc,
                    FK.value:"1",
                    FK.field:StrField(id: "total", need: false, hiden: false, rule:
                        JoRule(reg: "^\\d{0,100}$", nil_msg: "请选择数量".loc, err_msg: "请选择数量".loc)),
                    ]
            
            self.mo.model = field.mutable_dictionary
        }
        
        override func mo_detail_reload() {
            var store_count = mo.detail[int:"stock",0]
            if store_count == 0
            {
                store_count = mo.detail[int:"total",0]
            }
            let selectedCount =  mo.model[int:FK.value,0]
            if selectedCount > store_count
            {
                self.mo.model[FK.value] = "1"
                mo_model_reload()
            }
            
            if store_count < 1{
                
            }
            self.numControl.limit = NumLimit(min: 1, minMask:"选择有效的[XX]数量".replaceVars(values: OrderScheme.default.goodsTag), max: store_count, maxMask: "没有足够的库存".loc)
            switch self.specTask {
            case .group(info: _):
                self.numControl.limit = NumLimit(min: 1, minMask: "选择有效的商品数量".loc, max: 1, maxMask: "拼团商品限购1份".loc)
            default:
                break
            }
            
        }
        
        override func didLayoutRules() {
            
            fieldNameL.ui.font(font: valueFont).text(color: ._foreground).text(place_holder)
            fieldNameL.setContentConstrainToHighLever()
            numControl.setContentConstrainToHighLever()
            numControl.changeNumValue = {[weak self] (num) in
                let value = "\(num)"
                self?.mo.model[FK.value] = value
                self?.save(value)
            }
        }
        
        override func mo_model_reload() {
            super.mo_model_reload()
            _ = fieldNameL.ui.font13.text(color: ._foreground)
        }
        
        override var intrinsicContentSize: CGSize{
            return CGSize(width: Swidth, height: 60)
        }
    }
    
    class CurrentBar: JoView {
        public var specTask = SpecTask.default{
            didSet{
                mo_detail_reload()
                mo_model_reload()
            }
        }

     
        
        let imgV = UIImageView()
        let priceL = UILabel()
        let specL = UILabel()
        let store_numL = UILabel()
        override func addLayoutRules() {
            let line = UIView()
            eelay = [
                [imgV,[ee.T.L,[AppTheme.edge,AppTheme.edge]],80,"80"],
                [priceL,[imgV,ee.Y.R,ee.Y.L,[-4,10]]],
                [store_numL,[priceL,ee.B],[priceL,ee.R,ee.L,8],],
                [specL,[imgV,ee.Y.R,ee.Y.L,[24,10]],[ee.R,-AppTheme.edge]],
                [line,[ee.L.B.R],"\(TP.separatorHeight)"],
            ]
            line.backgroundColor = UIColor.table_bg_color
            imgV.backgroundColor = UIColor(shex: "#c1c1c122")
            imgV.bsui.set(radius: 4, width: 2, color: UIColor(shex:"#eee"))
        }
        
        
        var recentSpec:NSMutableDictionary = NSMutableDictionary(){
            didSet{
                let thumb = recentSpec["thumb",""]
                if thumb.len > 0
                {
                    imgV.img_url = thumb
                }
            }
        }
        
        override func mo_detail_reload() {
            imgV.img_url = mo.detail["thumb",""]

            if  Goods.hasSpec(goods: mo.detail)
            {
                let minprice = mo.detail[float:"minprice",0]
                let maxprice = mo.detail[float:"maxprice",0]
                
                //未选择规格选用外部价格
                let price = mo.detail.possible(specTask.hasnoSpecPriceNode, default: "0").CGFloatV
                if minprice < maxprice{
                    priceL.attributedText = specTask.priceTag + "\(minprice.price_display) ~ \(maxprice.price_display)".ui.color(hex: "#FE5A5A").font16.astring
                }
                else{
                    priceL.attributedText = specTask.priceTag + "\(price.price_display)".ui.color(hex: "#FE5A5A").font16.astring
                }
                
                specL.attributedText = mo.detail["title",""].ui.font11.cl_888.astring
//                specL.attributedText = "请选择属性/规格".ui.font11.cl_888.astring
                store_numL.text = ""
            }
            else{
                //没有规格项
                let marketprice = mo.detail[float:specTask.hasnoSpecPriceNode,0]
  
                var store_count = mo.detail[int:"total",0]
                if store_count == 0
                {
                    store_count = mo.detail[int:"stock",0]//团购库存
                }
                
                priceL.attributedText = specTask.priceTag +  "\(marketprice.price_display)".ui.color(hex: "#FE5A5A").font16.astring +   "   库存  \(store_count)".ui.cl_888.font12.astring
                specL.attributedText = mo.detail.possible("title","subtitle", default: "").ui.font11.cl_888.astring
                specL.lineBreakMode = .byTruncatingTail
                store_numL.text = ""
                
                
            }
            
        }
        
        override func mo_model_reload() {

            let key = mo.model["spec_key_name",""]
            if key.len < 1{//无规格
                let minprice = mo.detail[float:"minprice",0]
                let maxprice = mo.detail[float:"maxprice",0]
                let price = mo.detail.possible(specTask.hasnoSpecPriceNode, default: "0").CGFloatV
                
                if minprice < maxprice{
                    priceL.attributedText = specTask.priceTag + "\(minprice.price_display) ~ \(maxprice.price_display)".ui.color(hex: "#FE5A5A").font16.astring
                }else{
                    priceL.attributedText = specTask.priceTag + "\(price.price_display)".ui.color(hex: "#FE5A5A").font16.astring

                }
                specL.attributedText = mo.detail["title",""].ui.font11.cl_888.astring
//                specL.attributedText = "请选择属性/规格".ui.font11.cl_888.astring
                store_numL.text = ""
                imgV.img_url = mo.detail["thumb",""]
                
            }
            else{//有效规格
                let store_count = mo.model[int:"stock",0]
                let uni_price = mo.model[float:specTask.specPriceNode,0.0]
                
                priceL.attributedText = specTask.priceTag + "\(uni_price.price_display) ".ui.color(hex: "#FE5A5A").font16.astring
                specL.attributedText = "\(mo.model["spec_key_name",""])".ui.font11.cl_888.astring
                specL.lineBreakMode = .byTruncatingTail

                store_numL.attributedText = "库存：\(store_count)".ui.font11.cl_888.astring
                
            }
        }
    }
    
    
    open class ConfirmBar: EeBottomBar {
        public var pramasGetter:()->(Bool,[String:Any]) = { return (true,[String:Any]())}
        
        open override func didSetController(controller: UIViewController?) {
            numF.controller = self.controller
        }
        
        public let numF = NumBorderField()
        public var nextBar = SpecNextBar()
        
        
        public let priceL = UILabel()
        public let store_numL = UILabel()
        
        public var nextAction:([String:Any],SpecSelectorNext)->Void = {_,_ in}
        open override var contentHeight: CGFloat{
            get{
                return 49.0
            }
        }
        
        
        open override func addLayoutRules() {
            let h = 38
            let line = UIView()
            contentView.eelay = [
            
//                [cartBt,[ee.L.X,ee.L.R,[12,-5]],[ee.Y],"\(h)"],
//                [buyBt,[ee.R.X,ee.R.L,[-12,5]],[ee.Y],"\(h)"],
                [nextBar.view,[ee.L.R.Y],"\(h)"],
//                [line,[ee.T.L.R],"\(TP.separatorHeight)"]
//                [cartBt,[ee.T.B],[ee.X,ee.R],[ee.L]],
//                [buyBt,[ee.T.B],[ee.X,ee.L],[ee.R]],
            ]
//            line.backgroundColor = ._separator
            nextBar.setNeedsLayout()
            nextBar.setNeedsDisplay()
            
            //            priceL.attributedText = "单价 ¥：".ui.sim_font(15).cl_666.astring + "1000".ui.color(hex: UIColor.main_hex).font15.astring
            //            store_numL.attributedText = "库存 100".ui.sim_font(15).cl_666.astring
            //            buyBt.isEnabled = false
            //            cartBt.isEnabled = false
            weak var wself = self
            nextBar.nextPressed = {
                next in
                wself?.nextStep(next: next)
            }
        }
        
        open func nextStep(next:SpecSelectorNext) {
            var values = [String:Any]()
            switch next {
            case .加入购物车:
                if mo.detail["canAddCart",true.tag] == false.tag
                {
                    "该商品不可加入购物车".loc.alert()
                    return
                }
                values["id"] = mo.detail["id",""]
            default:
                break
            }
            
            let info = nextCheck()
            
            if info.0
            {
                weak var wself = self
                let vs = values + info.1
                EeAuthControl.getUser { (success, msg, user) in
                    wself?.nextAction(vs,next)
                }
            }

        }
        
       
        
        
        open func nextCheck()->(Bool,[String:Any]){
            
            
            var valid = false
            
            var info = [String:Any]()
            let params = pramasGetter()
            if params.0
            {
                
                let values = params.1.mutable_dictionary
                valid = params.0
                info["goodsid"] = mo.detail["id",""]
                info["total"] = values["total","0"]
                
                if Goods.hasSpec(goods: mo.detail)
                {
                    info["optionid"] = mo.model["optionid",""]
                }
                else{
                    
                    if store_num <= 0{
                        "没有库存".alert()
                        valid = false
                    }
                }
            }            
            return (valid,info)
        }
        
        
        open var store_num:Int{
            get{
                let num = mo.detail.possible("stock","total", default: "0")
                return Int(num) ?? 0
            }
        }
        
        
        open override func mo_model_reload() {
            let key = mo.model["key",""]
            if key.len < 1{
                store_numL.attributedText = "请选择规格".loc.ui.font12.cl_999.astring
                priceL.attributedText = "".ui.font12.cl_999.astring
                //                buyBt.isEnabled = false
                //                cartBt.isEnabled = false
            }
            else{
                let store_count = mo.model[int:"stock",0]
                let uni_price = mo.model[float:"shop_price",0.0]
                
                priceL.attributedText = "\("单价".loc) \("¥".loc)：".ui.font12.cl_666.astring + "\(uni_price.price_display)".ui.color(hex: UIColor.main_hex).font13.astring
                store_numL.attributedText = "\("库存".loc) \(store_count)".ui.font12.cl_666.astring
                let selectedCount = numF.mo.model[int:FK.value,1]
                numF.limit = NumLimit(min: 1, minMask: "选择有效的商品数量".loc, max: store_count, maxMask: "没有足够的库存".loc)
                if selectedCount > store_count
                {
                    numF.mo.model[FK.value] = "1"
                    numF.mo_model_reload()
                }
                
                if store_count < 1{
                    //                    buyBt.isEnabled = false
                    //                    cartBt.isEnabled = false
                }
            }
        }
        
        open var validInfo:(Bool,String){
            get{
                let key = mo.model["key",""]
                if key.len < 1{
                    return (false,"请选择规格".loc)
                }
                return (true,"")
            }
        }
        
        
    }
}

